﻿/*
 * 设计模式 - 策略模式
 * 定义一系列的算法类,将每个算法类分别封装起来,让他们可以互相替换
 */

// 未使用 IOC
//EFReps efReps = new EFReps();
//RedisReps redisReps = new RedisReps();


//var service = new AppService(efReps);

//var service2 = new AppService(redisReps);

//service.Create(new object());
//service2.Create(new object());


//使用IOC改造代码
// 使用微软自带IOC
//using Microsoft.Extensions.DependencyInjection;

//var services = new ServiceCollection();
//services.AddTransient<IReps, EFReps>();
//services.AddTransient<AppService>();
//var builder = services.BuildServiceProvider();

//var appService = builder.GetRequiredService<AppService>();
//appService.Create(null);

// 使用AutoFac

using Autofac;

var builder = new ContainerBuilder();
builder.RegisterType<EFReps>().As<IReps>().AsImplementedInterfaces().PropertiesAutowired();
builder.RegisterType<RedisReps>().As<IReps>().AsImplementedInterfaces().PropertiesAutowired();
builder.RegisterType<AppService>().PropertiesAutowired();
var services = builder.Build();

using var scope = services.BeginLifetimeScope();
var appService = scope.Resolve<AppService>();
appService.Create(null);


public interface IReps
{
    void Add(object obj);
}

public class EFReps : IReps
{
    public void Add(object obj)
    {
        Console.WriteLine("使用了EF仓储");
    }
}

public class RedisReps : IReps
{
    public void Add(object obj)
    {
        Console.WriteLine("使用了Redis仓储");
    }
}

public class AppService
{
    private readonly IReps _reps;


    public AppService(IReps reps)
    {
        _reps = reps;
    }

    public void Create(object obj)
    {
        _reps.Add(obj);
    }
}